package com.atguigu.srb.core.controller.api;


import com.atguigu.common.result.R;
import com.atguigu.common.utils.JwtUtils;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import io.jsonwebtoken.Jwt;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2022-09-13
 */
@RestController
@RequestMapping("/api/core/userAccount")
public class ApiUserAccountController {

    @Resource
    TransFlowService transFlowService;
    @Resource
    UserAccountService userAccountService;

    @PostMapping("/commitCharge/{chargeAmt}")
    public R commitCharge(@PathVariable BigDecimal chargeAmt , HttpServletRequest request){

        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        String form = userAccountService.commitCharge(chargeAmt,userId);
        return R.ok().data("form",form);
    }
    @PostMapping("/notify")
    public String notifyCommitCharge(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> map = RequestHelper.switchMap(parameterMap);
        String agentBillNo = (String)map.get("agentBillNo");
        //做幂等性校验 判断交易是否已经存在
        boolean flag = transFlowService.isSaveTransFlow(agentBillNo);
        if (!flag){
            userAccountService.notifyCommitCharge(map);
           return "success";
        }
        return "success";
    }
    @GetMapping("/getUserAccount")
    public R getUserAccount(HttpServletRequest request){
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        BigDecimal account = userAccountService.getUserAccount(userId);
        return R.ok().data("account",account);
    }

}

